package com.yzg.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @author misterWei
 * @create 2020年06月27号:21点20分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.SemaphoreTest")
public class SemaphoreTest {
    public static void main(String[] args) {
        /**
         * 信号量,相当于 获取令牌,释放令牌
         */
        Semaphore semaphore  = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    log.info("拿取{}",semaphore.availablePermits());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    //log.info(String.valueOf(finalI));
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                    log.info("释放{}",semaphore.availablePermits());
                }

            },"t"+i).start();
        }
    }
}
